
<template>
  <div class="kitchen-container">
    <div class="header">
      <h2>后厨工作台</h2>
      <div class="tabs">
        <el-tag v-for="tab in tabs" :key="tab" 
                :type="activeTab === tab? 'primary' : 'info'"
                @click="filterTasks(tab)">
          {{ tab }}
        </el-tag>
      </div>
    </div>
    

    <div class="order-container">
      <!-- 左侧订单列表 -->
      <div class="order-list">
        <div v-for="task in filteredTasks" :key="task.taskId" 
             class="order-card" 
             :class="{ 'active': activeTask?.taskId === task.taskId }"
             @click="selectTask(task)">
          <div class="order-header">
            <span class="order-id">订单ID: {{ task.taskId }}</span>
            <span class="table-number">餐台: {{ task.tableId }}</span>
          </div>
          <div class="order-time">
            <span>{{ formatTime(task.createTime) }}</span>
            <span class="duration">{{ calculateDuration(task.createTime) }}</span>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(task.taskStatus)" size="small">
              {{ task.taskStatus }}
            </el-tag>
          </div>
          <div class="order-dishes-preview">
            <span v-for="dish in task.dishes.slice(0, 2)" :key="dish.dish.dishId" class="dish-preview">
              {{ dish.dish.dishName }} ×{{ dish.quantity }}
            </span>
            <span v-if="task.dishes.length > 2" class="more-dishes">+{{ task.dishes.length - 2 }}更多</span>
          </div>
        </div>
        <!-- 无任务提示 -->
        <div v-if="!hasPendingTasks" class="no - task - prompt">
          <div class="icon - box">
            <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
              <rect x="16" y="16" width="32" height="32" rx="4" ry="4" fill="#ccc"></rect>
              <rect x="24" y="20" width="16" height="4" fill="#ccc"></rect>
              <rect x="28" y="32" width="8" height="4" fill="#ccc"></rect>
            </svg>
          </div>
          <p>暂无待制作任务，休息一下吧！</p>
        </div>
      </div>

      <!-- 右侧订单详情 -->
      <div class="order-detail" v-if="activeTask">
        <div class="detail-header">
          <div class="detail-title">
            <h3>订单详情</h3>
            <el-tag :type="getStatusType(activeTask.taskStatus)" size="medium">
              {{ activeTask.taskStatus }}
            </el-tag>
          </div>
          <div class="order-meta">
            <div><span class="label">订单ID:</span> {{ activeTask.orderId }}</div>
            <div><span class="label">餐台编号:</span> {{ activeTask.tableId }}</div>
            <div><span class="label">下单时间:</span> {{ formatTime(activeTask.createTime) }}</div>
            <div><span class="label">下单时长:</span> {{ calculateDuration(activeTask.createTime) }}</div>
          </div>
        </div>

        <div class="dishes-list">
          <div v-for="dish in activeTask.dishes" :key="dish.dish.dishId" class="dish-item">
            <div class="dish-info">
              <span class="dish-name">{{ dish.dish.dishName }}</span>
              <span class="dish-quantity">{{ dish.quantity }}份</span>
              <span v-if="dish.remark" class="dish-remark">{{ dish.remark }}</span>
            </div>
            <div class="dish-actions">
              <el-tag :type="getDishStatusType(dish.status)" size="small">
                {{ dish.status }}
              </el-tag>
              <el-button v-if="dish.status!== '已完成'" size="small" 
                         @click="markDishAsDone(dish)" 
                         :type="dish.status === '待制作'? 'primary' : 'warning'">
                {{ dish.status === '待制作'? '开始制作' : '完成出菜' }}
              </el-button>
            </div>
          </div>
        </div>

        <div class="special-notes">
          <h4>特殊要求</h4>
          <p>{{ activeTask.dishes.find(d => d.remark)?.remark || '无特殊要求' }}</p>
        </div>

        <div class="order-actions">
          <el-button type="success" :disabled="!canCompleteTask" @click="completeCurrentTask">
            完成全部出菜
          </el-button>
          <el-button type="info" @click="printTask">
            打印订单
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { fetchKitchenTasks, updateDishStatus,completeTask } from '@/api/kitchen'
import type { TaskDTO } from './types'

const tabs = ['全部', '前菜', '主食', '小吃', '甜品', '饮料']
const activeTab = ref('全部')
const activeTask = ref<TaskDTO | null>(null)
const tasks = ref<TaskDTO[]>([])

// 计算属性
const filteredTasks = computed(() => {
  if (activeTab.value === '全部') return tasks.value
  return tasks.value.filter(task => 
    task.dishes.some(dish => dish.dish.category === activeTab.value))
})

const canCompleteTask = computed(() => {
  return activeTask.value?.dishes.every(dish => dish.status === '已完成')
})

const hasPendingTasks = computed(() => {
  return tasks.value.some(task => task.dishes.some(dish => dish.status!== '已完成'));
})

onMounted(async () => {
  await loadTasks()
  setInterval(loadTasks, 5000) // 每5秒检查一次新任务
})

// 方法
const loadTasks = async () => {
  try {
    const response = await fetchKitchenTasks()
    tasks.value = response.data
    if (tasks.value.length > 0 && !activeTask.value) {
      activeTask.value = tasks.value[0]
    }
  } catch (error) {
    console.error('加载任务失败:', error)
  }
}

function selectTask(task: TaskDTO) {
  activeTask.value = task
}

function filterTasks(category: string) {
  activeTab.value = category
}

async function markDishAsDone(dish: any) {
  if (!activeTask.value) return
  
  try {
    let newStatus: '制作中' | '已完成'
    
    if (dish.status === '待制作') {
      newStatus = '制作中'
    } else if (dish.status === '制作中') {
      newStatus = '已完成'
    } else {
      return
    }
    
    await updateDishStatus({
      taskId: activeTask.value.taskId,
      dishId: dish.dish.dishId,
      status: newStatus
    })
    
    // 更新本地状态
    const taskIndex = tasks.value.findIndex(t => t.taskId === activeTask.value?.taskId)
    if (taskIndex !== -1) {
      const dishIndex = tasks.value[taskIndex].dishes.findIndex(d => d.dish.dishId === dish.dish.dishId)
      if (dishIndex !== -1) {
        tasks.value[taskIndex].dishes[dishIndex].status = newStatus
        if (newStatus === '制作中') {
          tasks.value[taskIndex].dishes[dishIndex].startTime = new Date().toISOString()
        } else if (newStatus === '已完成') {
          tasks.value[taskIndex].dishes[dishIndex].finishTime = new Date().toISOString()
        }
      }
    }
    
    // 更新任务状态
    updateTaskStatus()
  } catch (error) {
    console.error('更新菜品状态失败:', error)
  }
}

function updateTaskStatus() {
  if (!activeTask.value) return
  
  const task = activeTask.value
  if (task.dishes.every(d => d.status === '已完成')) {
    task.taskStatus = '已完成'
  } else if (task.dishes.some(d => d.status === '制作中')) {
    task.taskStatus = '处理中'
  } else {
    task.taskStatus = '待处理'
  }
}

async function completeCurrentTask() {
  if (!activeTask.value || !canCompleteTask.value) return
  
  try {
    await completeTask(activeTask.value.taskId)
    
    // 从本地列表中移除已完成任务
    const index = tasks.value.findIndex(t => t.taskId === activeTask.value?.taskId)
    if (index !== -1) {
      tasks.value.splice(index, 1)
      if (tasks.value.length > 0) {
        activeTask.value = tasks.value[0]
      } else {
        activeTask.value = null
      }
    }
  } catch (error) {
    console.error('完成任务失败:', error)
  }
}

function printTask() {
  window.print()
}

function getStatusType(status: string) {
  switch (status) {
    case '已完成': return'success'
    case '待上菜': return ''
    case '制作中': return 'warning'
    case '待制作': return 'info'
    default: return 'info'
  }
}

function getDishStatusType(status: string) {
  switch (status) {
    case '已完成': return'success'
    case '制作中': return 'warning'
    case '待制作': return 'info'
    default: return 'info'
  }
}

function formatTime(timeString: string) {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString()
}

function calculateDuration(startTime: string) {
  if (!startTime) return ''
  const start = new Date(startTime)
  const now = new Date()
  const diff = Math.floor((now.getTime() - start.getTime()) / 60000) // 分钟
  return `${diff}分钟`
}

async function handleNewTask(task: TaskDTO) {
  // 检查是否已存在相同任务
  const existingIndex = tasks.value.findIndex(t => t.taskId === task.taskId)
  
  if (existingIndex === -1) {
    // 新任务，添加到列表开头
    tasks.value.unshift(task)
    
    // 如果没有当前选中的任务，自动选中第一个
    if (!activeTask.value) {
      activeTask.value = tasks.value[0]
    }
    
    // 播放新订单提示音或显示通知
    playNotificationSound()
  } else {
    // 更新现有任务
    tasks.value[existingIndex] = task
  }
}

// 简单的通知音效
function playNotificationSound() {
  const audio = new Audio('/notification.mp3') // 准备一个简短的提示音
  audio.play().catch(e => console.log('无法播放提示音:', e))
}
</script>

<style scoped>
.kitchen-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.tabs.el-tag {
  cursor: pointer;
  margin-bottom: 5px;
}

.order-container {
  display: flex;
  flex: 1;
  gap: 20px;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-list {
  width: 300px;
  overflow-y: auto;
  border-right: 1px solid #ebeef5;
  padding-right: 20px;
}

.order-card {
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 6px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s;
}

.order-card:hover {
  background-color: #ecf5ff;
}

.order-card.active {
  background-color: #e6f7ff;
  border-left: 3px solid #409eff;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 500;
}

.order-time {
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.duration {
  color: #f56c6c;
}

.order-status {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
}

.order-dishes-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  font-size: 13px;
  color: #606266;
}

.dish-preview {
  background-color: #e6f7ff;
  padding: 2px 6px;
  border-radius: 3px;
}

.more-dishes {
  color: #909399;
  font-style: italic;
}

.order-detail {
  flex: 1;
  padding: 0 20px;
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-title {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.order-meta {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-top: 15px;
  font-size: 14px;
}

.order-meta.label {
  color: #909399;
  margin-right: 8px;
}

.dishes-list {
  margin: 20px 0;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #ebeef5;
}

.dish-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.dish-name {
  font-weight: 500;
  min-width: 120px;
}

.dish-remark {
  color: #e6a23c;
  font-size: 14px;
}

.dish-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.special-notes {
  margin-top: 30px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.special-notes h4 {
  margin-bottom: 10px;
  color: #606266;
}

.special-notes p {
  color: #606266;
  line-height: 1.6;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.no - task - prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  text-align: center;
  color: #999;
}

.icon - box {
  margin-bottom: 10px;
}

@media print {
 .order-list,.header,.order-actions {
    display: none;
  }
 .order-container {
    display: block;
  }
 .order-detail {
    padding: 0;
  }
}
</style>
